package com.ilop.siteraudio.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.myapplication_ccc.MainActivity;
import com.ilop.siteraudio.R;
import com.ilop.siteraudio.activity.FAQActivity;
import com.ilop.siteraudio.data.bean.ReportBean;
import com.ilop.siteraudio.data.util.ReportDaoUtil;
import com.ilop.siteraudio.util.ByteUtils;
import com.ilop.siteraudio.util.FileUtils;

import java.util.Arrays;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author skygge
 * @date 2/1/21.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class ReportFragment extends Fragment {

    private static final String TAG = ReportFragment.class.getSimpleName();

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_battery)
    TextView mReportBattery;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_work)
    TextView mReportWork;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_sensor)
    TextView mReportSensor;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_alarm)
    TextView mReportAlarm;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_tests)
    TextView mReportTimes;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_days)
    TextView mReportLastTest;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.report_duration)
    TextView mReportDuration;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.layout_report_1)
    RelativeLayout mBatteryLayout;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.layout_report_3)
    RelativeLayout mSensorLayout;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.layout_report_4)
    RelativeLayout mAlarmLayout;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.layout_report_6)
    RelativeLayout mAlarmNumberLayout;

    private ReportBean mReportBean;

    public static ReportFragment newInstance(String filePath, long reportId) {
        Bundle args = new Bundle();
        args.putString("REPORT_PATH", filePath);
        args.putLong("REPORT_ID", reportId);
        ReportFragment fragment = new ReportFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_report, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        assert getArguments() != null;
        String path = getArguments().getString("REPORT_PATH");
        long reportId = getArguments().getLong("REPORT_ID");
        mReportBean = ReportDaoUtil.getInstance().getReportById(reportId);
        Log.i(TAG, "REPORT_PATH: " + path);
        byte[] mDeviceData = getValidData(path);
        initAnalysis(mDeviceData);
        insertOrReplaceData();
    }

    @SuppressLint("SetTextI18n")
    private void initAnalysis(byte[] mDeviceData) {
        if (mDeviceData != null) {
            System.out.println(Arrays.toString(mDeviceData));
            String mWorkTime = ByteUtils.toHexString(mDeviceData[1]) + ByteUtils.toHexString(mDeviceData[2]) + ByteUtils.toHexString(mDeviceData[3]);
            double work =  Integer.parseInt(mWorkTime, 16)/24f;
            mReportWork.setText(ByteUtils.getDoubleToString(work) + getString(R.string.days));

            String mBattery = ByteUtils.toHexString(mDeviceData[4]) + ByteUtils.toHexString(mDeviceData[5]);
            double batter =  Integer.parseInt(mBattery, 16)/1000f;
            mReportBattery.setText(ByteUtils.getDoubleToString(batter) + "V");
            if (batter < 2.6f) {
                mBatteryLayout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.orange));
            }

            if (mDeviceData[6] == 0) {
                mReportSensor.setText("OK");
            }else {
                mReportSensor.setText("NG");
                mSensorLayout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.red));
            }

            String mTestNum = ByteUtils.toHexString(mDeviceData[7]) + ByteUtils.toHexString(mDeviceData[8]);
            int textNum = Integer.parseInt(mTestNum, 16);
            mReportTimes.setText(textNum + getString(R.string.times));

            String mTestTime = ByteUtils.toHexString(mDeviceData[9]) + ByteUtils.toHexString(mDeviceData[10]);
            double testNum =  Integer.parseInt(mTestTime, 16)/24f;
            mReportLastTest.setText(ByteUtils.getDoubleToString(testNum) + getString(R.string.days));

            String mAlarmNum = String.valueOf(mDeviceData[11]);
            mReportAlarm.setText(mAlarmNum + getString(R.string.times));
            if (mDeviceData[11] != 0) {
                mAlarmLayout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.orange));
            }

            String mAlarmTime = ByteUtils.toHexString(mDeviceData[12]) + ByteUtils.toHexString(mDeviceData[13]);
            double alarmNum =  Integer.parseInt(mAlarmTime, 16)/24f;
            if (alarmNum > 0) {
                mAlarmNumberLayout.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.orange));
            }
            mReportDuration.setText(ByteUtils.getDoubleToString(alarmNum) + getString(R.string.days));
        }
    }

    private void insertOrReplaceData() {
        String battery = mReportBattery.getText().toString();
        String workTime = mReportWork.getText().toString();
        String sensorStatus = mReportSensor.getText().toString();
        String smokeAlarms = mReportAlarm.getText().toString();
        String lastAlarmDuration = mReportDuration.getText().toString();
        String testAlarms = mReportTimes.getText().toString();
        String lastTestDuration = mReportLastTest.getText().toString();
        mReportBean.setBattery(battery);
        mReportBean.setWorkTime(workTime);
        mReportBean.setSensorStatus(sensorStatus);
        mReportBean.setSmokeAlarms(smokeAlarms);
        mReportBean.setLastAlarmDuration(lastAlarmDuration);
        mReportBean.setTestAlarms(testAlarms);
        mReportBean.setLastTestDuration(lastTestDuration);
        ReportDaoUtil.getInstance().getReportDao().insertOrReplace(mReportBean);
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.layout_report_1, R.id.layout_report_2, R.id.layout_report_3, R.id.layout_report_4,
            R.id.layout_report_5, R.id.layout_report_6, R.id.layout_report_7})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_report_1:
                onSkipToFAQ(1);
                break;
            case R.id.layout_report_2:
                onSkipToFAQ(2);
                break;
            case R.id.layout_report_3:
                onSkipToFAQ(3);
                break;
            case R.id.layout_report_4:
                onSkipToFAQ(4);
                break;
            case R.id.layout_report_5:
                onSkipToFAQ(5);
                break;
            case R.id.layout_report_6:
                onSkipToFAQ(6);
                break;
            case R.id.layout_report_7:
                onSkipToFAQ(7);
                break;
        }
    }

    private void onSkipToFAQ(int param){
        Intent intent = new Intent(getActivity(), FAQActivity.class);
        intent.putExtra("faq_type", param);
        Objects.requireNonNull(getActivity()).startActivity(intent);
    }

    private byte[] getValidData(String path){
        boolean isExists = FileUtils.isFileExists(path);
        if (isExists) {
            byte[] array = MainActivity.userAudioRun(path);
            System.out.println(Arrays.toString(array));
            if (array[4] != 16) {
                return null;
            }
            try {
                byte[] newArray = new byte[16];
                System.arraycopy(array, 5, newArray, 0, 16);
                return newArray;
            }catch (Exception e){
                return null;
            }
        }else {
            Toast.makeText(getActivity(), "路径下无文件", Toast.LENGTH_SHORT).show();
            return null;
        }
    }
}
